package com.vmware.elastic.high;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.List;

/**
 * @apiNote 聚合查询
 */
public class DocumentAggregateQuery {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        SearchRequest request = new SearchRequest("vmware");
        //最大值查询
//        MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("maxAge").field("age");

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");//分组查询

        request.source(new SearchSourceBuilder().aggregation(termsAggregationBuilder));//构建查询，设置为全量查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        for (Aggregation aggregation : response.getAggregations()) {
            ParsedLongTerms terms = (ParsedLongTerms) aggregation;
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                System.out.println(bucket.getKeyAsString() + ":" + bucket.getDocCount());
            }
        }

        client.close();
    }
}
